import { history, request } from '@umijs/max';
import type { AutoCompleteProps } from 'antd';
import { AutoComplete, Input } from 'antd';
import { useEffect, useState } from 'react';

export default function SearchInput() {
  const { Search } = Input;

  const mockVal = (str: string) => ({
    value: str,
  });
  const filterData = (arr: string[], searchText: string) => {
    return arr
      .filter((item) => item.includes(searchText))
      .map((item) => mockVal(item));
  };

  const [data, setData] = useState<any>(null);

  useEffect(() => {
    const fetchFunctionData = async () => {
      try {
        const response = await request('/api/function');
        if (response.success) {
          setData(response.data.functionModule);
        } else {
          console.error('请求失败，错误代码:', response.errorCode);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    };

    fetchFunctionData();
  }, []);

  const [value, setValue] = useState('');
  const [anotherOptions, setAnotherOptions] = useState<
    AutoCompleteProps['options']
  >([]);

  const getPanelValue = (searchText: string) =>
    !searchText
      ? []
      : filterData(
          data.map((item: { name: any }) => item.name),
          searchText,
        );

  const onSelect = (name: string) => {
    console.log('onSelect', name);
    history.push(data.find((e: { name: string }) => e.name === name)!.path);
  };

  const onChange = (data: string) => {
    setValue(data);
  };
  return (
    // <Search
    //   placeholder="功能搜索"
    //   style={{ flex: '1', marginRight: '80px', width: '300px' }}
    //   allowClear
    //   onSearch={onSearch}
    // />
    <AutoComplete
      style={{ flex: '1', marginRight: '80px', width: '300px' }}
      value={value}
      options={anotherOptions}
      onSelect={onSelect}
      onSearch={(text) => setAnotherOptions(getPanelValue(text))}
      onChange={onChange}
    >
      <Search placeholder="功能搜索" allowClear></Search>
    </AutoComplete>
  );
}
